package web.controller.common;

import common.consts.Consts;
import common.consts.ContentType;
import common.validation.ValidationResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import service.AccountService;
import service.ServiceResponse;
import web.Routes;
import web.controller.Base;
import web.req.AvatarRequest;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by liuchang on 2015/6/24.
 */
@RestController
@RequestMapping(Routes.Common.AVATAR)
public class Avatar extends Base {

    private static final Logger logger = LoggerFactory.getLogger(Avatar.class);

    @Autowired
    private AccountService accountService;

    @RequestMapping(method = RequestMethod.POST, produces = ContentType.JSON)
    public ServiceResponse upload(@RequestBody AvatarRequest request) {
        ValidationResult result = request.validate();
        if (result.isFailed()) {
            return fail(result.getMessage());
        }

        long user = getUserIdFromAuthHeader();

        MultipartFile avatarFile = request.getFile();

        String fileType = avatarFile.getContentType();

        if (!(fileType.split("/")[0].equals("image"))) {
            return fail(Consts.i18nKey.PLEASE_SELECT_AN_IMAGE);
        }

        long size = avatarFile.getSize();
        if (size > Consts.MAX_UPLOAD_IMAGE_BYTES) {
            return fail(Consts.i18nKey.UPLOADED_FILE_EXCEED_MAX_SIZE);
        }

        try {
            InputStream is = avatarFile.getInputStream();
            ServiceResponse serviceResponse = accountService.uploadAvatar(user, is);
            return serviceResponse;
        } catch (IOException e) {
            e.printStackTrace();
            return fail(Consts.i18nKey.SYSTEM_ERROR);
        }
    }
}
